package com.huffman.smart_picture.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.huffman.smart_picture.common.exception.ErrorEnum;
import com.huffman.smart_picture.config.CosClientConfig;
import com.huffman.smart_picture.utils.ThrowUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
@Deprecated
public class FileManager {

    private static final long ONE_M = 1024 * 1024;

    private static final List<String> ALLOW_FILE_TYPE = Arrays.asList("jpg", "png", "jpeg", "webp");

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;


    public PictureUploadDto uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        //图片校验
        validPicture(multipartFile);
        //图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originFilename = multipartFile.getOriginalFilename();
        String uploadFilename = String.format("%s/%s.%s", DateUtil.format(new Date(), "yyyy-MM-dd"), uuid, FileUtil.getSuffix(originFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
        File file = null;
        PictureUploadDto pictureUploadDto = new PictureUploadDto();
        try {
            file = File.createTempFile(uploadPath, null);
            multipartFile.transferTo(file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            pictureUploadDto.setUrl(cosClientConfig.getHost()+"/"+uploadPath);
            pictureUploadDto.setPicName(originFilename);
            pictureUploadDto.setPicSize(FileUtil.size(file));
            pictureUploadDto.setPicWidth(picWidth);
            pictureUploadDto.setPicHeight(picHeight);
            pictureUploadDto.setPicScale(picScale);
            pictureUploadDto.setPicFormat(imageInfo.getFormat());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (file != null) {
                if (!file.delete()) {
                    log.error("delete file error,filePath={}", file.getAbsoluteFile());
                }
            }
        }

        return pictureUploadDto;
    }

    private void validPicture(MultipartFile multipartFile) {
        ThrowUtil.throwIf(multipartFile == null, ErrorEnum.UPLOAD_FILE_EMPTY, "文件不能为空");
        // 校验文件大小
        long size = multipartFile.getSize();
        ThrowUtil.throwIf(size > 2 * ONE_M, ErrorEnum.UPLOAD_FILE_OVERSIZE, "文件大小超过2MB");
        //校验文件类型
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtil.throwIf(!ALLOW_FILE_TYPE.contains(suffix), ErrorEnum.FILE_TYPE_ERROR, "文件类型错误");
    }
}
